/**
 * 
 */
package com.demo2do.boyle.backend.service.system.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.boyle.backend.service.system.PrincipalService;
import com.demo2do.boyle.common.entity.system.Principal;
import com.demo2do.core.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.service.impl.GenericServiceImpl;

/**
 * @author Leo
 *
 */
@Service("principalService")
public class PrincipalServiceImpl extends GenericServiceImpl<Principal> implements PrincipalService {

	@Autowired 
	private GenericDaoSupport genericDaoSupport;
	
	/*
     * (non-Javadoc)
     * @see com.demo2do.boyle.backend.service.PrincipalService#list()
     */
	@SuppressWarnings("unchecked")
	public List<Principal> list() {
		List<Principal> Principals = genericDaoSupport.searchForList("FROM Principal");
		return Principals;
	}

	/*
	 * (non-Javadoc)
	 * @see com.demo2do.boyle.backend.service.PrincipalService#create(com.demo2do.boyle.backend.entity.security.Principal)
	 */
	public void create(Principal principal) {
		
		List<Principal> principals = this.list(principal.getMobile());
		
		if(!principals.isEmpty()) {
			
			throw new BusinessException("该手机号码已被注册,请填写其他手机号码");
		
		} else {
			
			genericDaoSupport.save(principal.initialize());
		
		}
		
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.demo2do.boyle.backend.service.PrincipalService#loadPrincipal(java.lang.String)
	 */
	public Principal loadPrincipal(String mobile) {
		List<Principal> principals = this.list(mobile);
		return principals.isEmpty() ? null:principals.get(0);
	}

	/**
	 * List principal by mobile
	 * 
	 * @param mobile
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<Principal> list(String mobile) {
		return genericDaoSupport.searchForList("FROM Principal principal WHERE principal.disabled = false AND principal.mobile = :mobile", "mobile", mobile);
	}
	
	
	/* (non-Javadoc)
	 * @see com.demo2do.boyle.backend.service.system.PrincipalService#resetPassword(com.demo2do.boyle.common.entity.system.Principal)
	 */
	public void resetPassword(Principal principal) {
		genericDaoSupport.update(principal.resetPassword());
	}
	
}
